﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using outREACH.App_Code;
using System.Web.Security;

namespace outREACH
{
    public partial class Infrastructure : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!IsPostBack)
            {
                if (Request.Cookies["User"] != null)
                    txtUser.Text = Request.Cookies["User"].Value;
                if (Request.Cookies["Pass"] != null)
                    txtPass.Text = Request.Cookies["Pass"].Value;
                if (Request.Cookies["User"] != null && Request.Cookies["Pass"] != null)
                    chkRemember.Checked = true;
            } 
        }

        protected void Login_Click(object sender, EventArgs e)
        {
            if (chkRemember.Checked == true)
            {
                Response.Cookies["User"].Value = txtUser.Text;
                Response.Cookies["Pass"].Value = txtPass.Text;
                Response.Cookies["User"].Expires = DateTime.Now.AddMonths(2);
                Response.Cookies["Pass"].Expires = DateTime.Now.AddMonths(2);
            }
            else
            {
                Response.Cookies["User"].Expires = DateTime.Now.AddMonths(-1);
                Response.Cookies["Pass"].Expires = DateTime.Now.AddMonths(-1);
            }

            String hashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPass.Text, "sha1");
            List<Users> results = Users.GetUser();
            foreach (Users user in results)
            {
                if (txtUser.Text.ToString() == user.userName.ToString())
                {
                    Users u = Users.AuthorizeUser(txtUser.Text);
                    string hashedPassworddata = FormsAuthentication.HashPasswordForStoringInConfigFile(u.password.ToString(), "sha1");
                    if (hashedPassword.ToString() == hashedPassworddata.ToString())
                    {
                        Session["UserName"] = u.userName.ToString();
                        Session["Country"] = u.country.ToString();
                        //Session["roles"] = u.role.ToString();
                        FormsAuthentication.RedirectFromLoginPage(u.userName.ToString(), false);
                        InvalidUP.Visible = false;
                        Response.Redirect("~/Infrastructure/InfrastructureMem.aspx");
                    }
                    else
                    {
                        InvalidUP.Visible = true;
                    }
                    break;
                }
            }
        }
    }
}